﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace RiaToDalLinq.ProviderBase
{
    /// <summary>
    /// 
    /// </summary>
    internal class Nominator : ExpressionVisitor
    {
        private Func<Expression, bool> _funcCanBeEvaluated;
        private HashSet<Expression> _candidates;
        private bool _cannotBeEvaluated;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fnCanBeEvaluated"></param>
        internal Nominator(Func<Expression, bool> fnCanBeEvaluated)
        {
            _funcCanBeEvaluated = fnCanBeEvaluated;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        internal HashSet<Expression> Nominate(Expression expression)
        {
            _candidates = new HashSet<Expression>();
            this.Visit(expression);
            return _candidates;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        protected override Expression VisitExtension(Expression expression)
        {
            if (expression != null)
            {
                bool cannotBeEvaluated = _cannotBeEvaluated;
                _cannotBeEvaluated = false;
                base.Visit(expression);

                if (!_cannotBeEvaluated)
                {
                    if (_funcCanBeEvaluated(expression))
                    {
                        _candidates.Add(expression);
                    }
                    else
                    {
                        _cannotBeEvaluated = true;
                    }
                }

                _cannotBeEvaluated |= cannotBeEvaluated;
            }

            return expression;
        }
    }
}
